'use client'

import styles from "./TicketsPage.module.css";
import Search from "@/components/ui/Dashboard/Search/Search";
import {useEffect, useState} from "react";
import {getObj} from "@/services/api_service";
import {useRouter} from "next/navigation";
import Button from "@/components/ui/Button/Button";

type TypeTicket = {
    id: number;
    ticket_type_name: string;
    verification_code: string;
    user?: string;
    vehicle_registration_number?: string;
    vehicle_type?: string;
    departure_port_name: string;
    arrival_port_name: string;
    results: [];
    count: number;
};

export default function TicketsPage({searchParams}: {
    searchParams?: {
        search?: string;
        page?: string;
    };
}) {
    const search = searchParams?.search || '';
    let currentPage = Number(searchParams?.page) || 1;
    const [tickets, setTickets] = useState<TypeTicket[]>([]);
    const [totalPages, setTotalPages] = useState<number>(1);
    const router = useRouter();

    useEffect(() => {
        const getTickets = async () => {
            let tickets: TypeTicket;

            if (search) {
                tickets = await getObj(`/api/ships/tickets/details/?search=${search}&page=1`);
                currentPage = 1;
            } else {
                tickets = await getObj(`/api/ships/tickets/details/?search=${search}&page=${currentPage}`);
            }
            setTickets(tickets.results);
            setTotalPages(Math.ceil(tickets.count / 10));
        }
        getTickets();
    }, [search, currentPage]);

        const handlePageChange = (page: number) => {
        router.push(`/admin/tickets?search=${search}&page=${page}`);
    };

    return (
        <div className={styles.ticketPage}>
            <header className={styles.header}>
                <h1>Список транспортных средств</h1>
            </header>
            <div>
                <section className={styles.search_area}>
                    <Search placeholder={'Поиск по транспортным средствам'}/>
                </section>
                <section>
                    <div className={styles.tableContainer}>
                        <div className={styles.tableWrapper}>
                            <div className={styles.tableBack}>
                                <table className={styles.table}>
                                    <thead className="rounded-lg text-left text-sm font-normal">
                                    <tr>
                                        <th scope="col" className="px-3 py-5 font-medium">
                                            #
                                        </th>
                                        <th scope="col" className="px-3 py-5 font-medium">
                                            Тип билета
                                        </th>
                                        <th scope="col" className="px-3 py-5 font-medium">
                                            Код билета
                                        </th>
                                        <th scope="col" className="px-3 py-5 font-medium">
                                            Регистр. номер
                                        </th>
                                        <th scope="col" className="px-3 py-5 font-medium">
                                            Тип ТС
                                        </th>
                                        <th scope="col" className="px-3 py-5 font-medium">
                                            Пользователь
                                        </th>
                                        <th scope="col" className="px-3 py-5 font-medium">
                                            Порт отправления
                                        </th>
                                        <th scope="col" className="px-3 py-5 font-medium">
                                            Порт прибытия
                                        </th>
                                    </tr>
                                    </thead>
                                    <tbody className="bg-white">
                                    {tickets?.map((ticket) => (
                                        <tr
                                            key={ticket.id}
                                            className="w-full border-b py-3 text-sm last-of-type:border-none [&:first-child>td:first-child]:rounded-tl-lg [&:first-child>td:last-child]:rounded-tr-lg [&:last-child>td:first-child]:rounded-bl-lg [&:last-child>td:last-child]:rounded-br-lg"
                                        >
                                            <td className="whitespace-nowrap px-3 py-3">
                                                {ticket.id}
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-3">
                                                {ticket.ticket_type_name}
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-3">
                                                {ticket.verification_code}
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-3">
                                                {ticket.vehicle_registration_number ? ticket.vehicle_registration_number : 'Нет ТС'}
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-3">
                                                {ticket.vehicle_type}
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-3">
                                                {ticket.user}
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-3">
                                                {ticket.departure_port_name}
                                            </td>
                                            <td className="whitespace-nowrap px-3 py-3">
                                                {ticket.arrival_port_name}
                                            </td>
                                        </tr>
                                    ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </section>
            </div>
            <div className={styles.pagination}>
                {Array.from({length: totalPages}, (_, index) => (
                    <Button
                        key={index + 1}
                        type="button"
                        kind={index + 1 === currentPage ? "submit" : "secondary"}
                        content={`${index + 1}`}
                        onClick={() => handlePageChange(index + 1)}
                    />
                ))}
            </div>
        </div>
    );
};

